﻿using FFmpeg.AutoGen;
using System;

namespace FFmpegLib;

public sealed unsafe class FAVStream
{
    private AVStream* _ptr;
    private AVCodecContext* _codecCtx;

    public AVStream* Ptr => _ptr;
    public AVCodecContext* CodecCtx => _codecCtx;
    public AVCodecID CodecID { get => _codecCtx->codec_id; }

    public FAVStream(AVStream* stream, double totalSecs)
    {
        _ptr = stream;
        _codecCtx = FFmpegUtils.GetCodecCtx(stream->codecpar->codec_id, true, stream->codecpar);

        TimeUnit = (double)TimeBase.num / TimeBase.den;
        if (totalSecs > 0)
            TotalSecs = totalSecs;
        else
            TotalTimeStr = TimeSpan.FromSeconds(totalSecs).ToString();
    }



    public int Id { get => _ptr->id; }
    public int Index { get => _ptr->index; }
    public long Duration { get => _ptr->duration; }
    public long NbFrames { get => _ptr->nb_frames; }
    public AVRational TimeBase { get => _ptr->time_base; }
    public AVMediaType MediaType { get => _ptr->codecpar->codec_type; }

    #region Video
    public int Width { get => _ptr->codecpar->width; }
    public int Height { get => _ptr->codecpar->height; }
    public AVColorRange ColorRange { get => _ptr->codecpar->color_range; }
    #endregion

    #region Audio

    public int Channels { get => _ptr->codecpar->channels; }
    public int SampleRate { get => _ptr->codecpar->sample_rate; }
    public ulong ChannelLayout { get => _ptr->codecpar->channel_layout; }
    public long BitRate { get => _ptr->codecpar->bit_rate; }
    public long FrameSize { get => _ptr->codecpar->frame_size; }
    #endregion

    public double TimeUnit { get; private set; }

    public string TotalTimeStr { get; set; }

    /// <summary>
    /// 总时长s
    /// </summary>
    public double TotalSecs { get; private set; }

    /// <summary>
    /// 当前播放进度 ms(毫秒)
    /// </summary>
    public long CurMsPos { get; set; }

    /// <summary>
    /// 当前播放进度
    /// </summary>
    /// <returns></returns>
    public string GetCurMsStr()
    {
        //double curTimePos = TimeUnit * CurDurationPos;
        TimeSpan span = TimeSpan.FromSeconds(TimeUnit * CurMsPos);
        return span.ToString();
    }

}